package com.goldplusgold.tradedelay.app.trade.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.support.lib.widget.horizontallistview.SyncHorizontalScrollView;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.market.eventbus.DynaMessageEvent;
import com.goldplusgold.network.lib.http.protobuf.Market;
import com.goldplusgold.tradedelay.app.trade.adapter.AdapterPosition;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.Position;
import com.goldplusgold.tradedelay.app.trade.pojo.PositionList;
import com.goldplusgold.support.lib.utils.NetWorkConstant;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

/**
 * Created by admin on 2017/5/15.
 */

public class PositionsFragment extends BaseFragment implements Handler.Callback {
    @BindView(R.id.id_bottom_list_view_position)
    ListView mBottomListViewPosition;
    @BindView(R.id.id_text_view_title_position)
    TextView mTextViewTitlePosition;
    @BindView(R.id.head_content_horsv)
    SyncHorizontalScrollView mHeadContentHorsv;
    @BindView(R.id.id_head_list_view_position)
    LinearLayout idHeadListViewPosition;

    private Handler handler = new Handler(this);
    AdapterPosition mAdapterPosition;

    public static PositionsFragment newInstance() {

        Bundle args = new Bundle();

        PositionsFragment fragment = new PositionsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_position;
    }


    @Override
    protected void initView() {
        super.initView();

        mBottomListViewPosition.setFocusable(false);
        List<String> titles = Arrays.asList("多/空",
                "可用/手数",
                "开仓均价",
                "浮动盈亏",
                "持仓均价",
                "盯市盈亏");
        for (String str : titles) {
            View childView = LayoutInflater.from(getContext()).inflate(R.layout.item_horizontal_position, idHeadListViewPosition, false);
            TextView mTextViewHorizontal = (TextView) childView.findViewById(R.id.id_text_view_horizontal);
            mTextViewHorizontal.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
            mTextViewHorizontal.setText(str);
            idHeadListViewPosition.addView(childView);
        }

        mAdapterPosition = new AdapterPosition(getActivity());
        mAdapterPosition.setFragmentRef(getParentFragment());
        mAdapterPosition.addHead(mHeadContentHorsv);
        mHeadContentHorsv.setOnScrollListenter(mAdapterPosition);
        mBottomListViewPosition.setOnItemClickListener(mAdapterPosition);
        mBottomListViewPosition.setAdapter(mAdapterPosition);
        new LoadPositionsAsyncTask().execute(AsyncTask.TYPE_NET);
    }



    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
        }

        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQuoteDynaEventBus(DynaMessageEvent event) {
        if (event.getType() == Market.Category.QUOTEDYNA) {
            if (mAdapterPosition != null) {
                mAdapterPosition.setQuoteDyna(event.getQuoteDyna());
            }
        }

    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public class LoadPositionsAsyncTask extends AsyncTask<Void, Void, List<Position>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<Position> doInBackground(Void... params) {

            try {
                PositionList positionList = TradeService.getInstance().getPositionList("");
                if (positionList != null) {
                    return positionList.getPositions();
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage();
            }

            return null;
        }

        @Override
        protected void onPostExecute(List<Position> positionList) {
            super.onPostExecute(positionList);
            if (!isAvailableActivity()) {
                return;
            }
            if (positionList == null || positionList.isEmpty()) {
                return;
            }
            mAdapterPosition.setArrayList(new ArrayList(positionList));
        }
    }

    private void sendNetworkErrorMessage() {
        Message message = handler.obtainMessage();
        message.what = NetWorkConstant.NETWORK_ERROR_CODE;
        handler.sendMessage(message);
    }

}
